package com.school.information.core.service;

import com.school.information.core.exception.ServiceException;
import com.school.information.core.security.entity.WechatAppUser;
import com.school.information.entity.SysWechatUserEntity;
import com.school.information.enums.result.SysResultEnum;
import com.school.information.service.SysWechatUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
public class WechatAppUserServiceImpl implements UserDetailsService {
    @Resource
    private SysWechatUserService sysWechatUserService;

    /**
     * 根据用户小程序的openid获取用户信息 username存放的是小程序的openid
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("##进入后台小程序登录代码逻辑代码处理：{}", username);
        // 根据登录名获取用户信息
        SysWechatUserEntity wechatUser = sysWechatUserService.getByOpenid(username);
        if (Objects.isNull(wechatUser)) {
            log.error("##当前登录的小程序用户：{}不存在", username);
            throw new ServiceException(SysResultEnum.APP_USER_NO_EXISTED);
        }
        // 获取用户角色、权限信息  用户角色和权限信息保留一个即可
        WechatAppUser wechatAppUser = new WechatAppUser();
        wechatAppUser.setSysWechatUser(wechatUser);

        return wechatAppUser;
    }
}
